package com.mol.market.ui_v4;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.network.ApiResponse;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.ProductDetail;
import com.mol.market.demo.widget.LazyLoadListFragment;
import com.mol.market.ui.LoginActivity;
import com.mol.market.ui.core.LazyLoadAdapter;

import java.util.ArrayList;
import java.util.HashMap;

/**
 *
 * 产品评论列表页。
 *
 * Author: Andrew.Wang
 * Date  : 13-1-7
 */
public class ProductCommentsFragment extends LazyLoadListFragment
    implements View.OnClickListener, LoaderManager.LoaderCallbacks<ApiResponse> {

    private Session mSession;
    private SherlockFragmentActivity mActivity;
    private ProductDetail mProductDetail;
    private LazyLoadAdapter mCommentAdapter;
    private EditText mCommentText;
    private Button mSubmit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mActivity = getSherlockActivity();
        setRetainInstance(false);
        mSession = Session.get(mActivity);
        mProductDetail = (ProductDetail)
                getArguments().getSerializable(Constants.EXTRA_PRDUCT_DETAIL);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSession = null;
        mActivity = null;
        mProductDetail = null;
        mCommentAdapter = null;
        mCommentText = null;
        mSubmit = null;
    }

    @Override
    protected View initLayout(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_product_comments, container, false);
        mCommentText = (EditText) v.findViewById(R.id.et_comment);
        mSubmit = (Button) v.findViewById(R.id.ib_send);
        mSubmit.setOnClickListener(this);
        return v;
    }

    @Override
    protected LazyLoadAdapter initLazyLoadAdapter() {
        mCommentAdapter = new LazyLoadAdapter(
                this,
                null,
                R.layout.market_list_item_comment,
                new String[]{
                        Constants.KEY_COMMENT_AUTHOR,
                        Constants.KEY_COMMENT_DATE,
                        Constants.KEY_COMMENT_BODY},
                new int[]{
                        R.id.tv_author,
                        R.id.tv_time,
                        R.id.tv_comment});
        return mCommentAdapter;
    }

    @Override
    protected void load() {
        getLoaderManager().restartLoader(
                MarketAPI.ACTION_GET_COMMENTS, null, this);
    }

    @Override
    public Loader<ApiResponse> onCreateLoader(int id, Bundle args) {

        if (id == MarketAPI.ACTION_GET_COMMENTS) {
            return MarketAPI.initGetCommentsLoader(mActivity,
                    mProductDetail.getPid(), getSize(), getStart());
        } else if (id == MarketAPI.ACTION_ADD_COMMENT) {
            return MarketAPI.initAddCommentsLoader(mActivity, mProductDetail.getPid(),
                    mCommentText.getText().toString());
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<ApiResponse> loader, ApiResponse data) {

        switch (loader.getId()) {

            case MarketAPI.ACTION_GET_COMMENTS: {

                handleComments(data);
                break;
            }

            case MarketAPI.ACTION_ADD_COMMENT: {
                handleAddComment(data);
                break;
            }

        }
    }

    private void handleAddComment(ApiResponse response) {

        mSubmit.setEnabled(true);
        if (response.status == ApiResponse.STATUS_OK) {
            addMyComment();
            mCommentText.setText("");
            InputMethodManager imm =
                    (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mCommentText.getWindowToken(), 0);
            Utils.makeEventToast(getApplicationContext(), (String) response.result, false);
        } else {
            handlePostError(response.status);
        }
    }

    private void handleComments(ApiResponse response) {

        if (response.status == ApiResponse.STATUS_OK) {

            // 第一次获取总条目数
            if (!isHasTotalSize() && response.result instanceof HashMap) {
                Object item = ((HashMap<String, Object>) response.result)
                        .get(Constants.KEY_TOTAL_SIZE);
                if (item != null) {
                    setTotal(Utils.getInt(item.toString()));
                }
            }

            ArrayList<HashMap<String, Object>> result = (ArrayList<HashMap<String, Object>>)
                    ((HashMap<String, Object>) response.result).get(Constants.KEY_COMMENT_LIST);
            if (result != null) {
                getAdapter().addDataList(result);
            }
            loadSuccess();

        } else if (response.status == ApiResponse.STATUS_LOGIC_ERROR) {

            if (getSize() == 0) {

                // 暂无评论
                HashMap<String, Object> noData = new HashMap<String, Object>();
                noData.put(Constants.KEY_COMMENT_BODY, getString(R.string.hint_no_comments));
                getAdapter().addData(noData);
            }
            loadSuccess();
        } else {

            loadFailure();
        }
    }

    @Override
    public void onLoaderReset(Loader<ApiResponse> loader) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        if (v.getId() == R.id.ib_send) {

            if (!mSession.isLogin()) {
                // 登录
                Intent loginIntent = new Intent(mActivity, LoginActivity.class);
                startActivityForResult(loginIntent, 0);
                return;
            }

            String body = mCommentText.getText().toString();
            if (TextUtils.isEmpty(body)) {
                // 不能发表空内容
                Utils.makeEventToast(mActivity,
                        getString(R.string.alert_post_not_null), false);
            } else {
                mSubmit.setEnabled(false);
                getLoaderManager().restartLoader(MarketAPI.ACTION_ADD_COMMENT,
                        null, this);
                Utils.trackEvent(mActivity, Constants.GROUP_8,
                        Constants.DETAIL_POST_COMMENT);
            }
        }
    }

    /*
     * 显示我的评论信息
     */
    private void addMyComment() {
        String commentBody = mCommentText.getText().toString();
        HashMap<String, Object> comment = new HashMap<String, Object>();
        comment.put(Constants.KEY_COMMENT_BODY, commentBody);
        comment.put(Constants.KEY_COMMENT_AUTHOR, mSession.getUserName());
        comment.put(Constants.KEY_COMMENT_DATE, Utils.formatTime(System.currentTimeMillis()));
        mCommentAdapter.insertData(comment);
    }

    /*
     * 处理评论的异常信息
     */
    private void handlePostError(int statusCode) {
        switch (statusCode) {
            case 232:
                // 非法回复内容
                Utils.makeEventToast(mActivity, getString(R.string.alert_unsafe_word),
                        false);
                break;
            case 225:
                // 没有对应的帖子
                Utils.makeEventToast(mActivity,
                        getString(R.string.alert_product_not_exist), false);
                break;
            case 233:
                // 帐号被禁言
                Utils.makeEventToast(mActivity, getString(R.string.alert_user_forbidden),
                        false);
                break;
            default:
                // 网络问题
                Utils.makeEventToast(mActivity, getString(R.string.alert_post_error),
                        false);
                break;
        }
    }
}
